from fastapi import FastAPI
from fastapi.responses import JSONResponse
from database.connection import connect_to_mongo, close_mongo_connection, get_database
from database.init_db import init_database
from middleware.request_id import RequestIdMiddleware

# 导入新的 v1 API
from api.v1.auth import router as auth_v1_router
from api.v1.user import router as user_v1_router
from api.v1.note import router as note_v1_router
from api.v1.certificate import router as cert_v1_router
from api.v1.certificate_upload import router as cert_upload_v1_router
from api.v1.certificate_refresh import router as cert_refresh_v1_router

app = FastAPI(
    title="SAC API",
    description="基于 FastAPI 的生产级认证系统 - 字节火山引擎风格API设计",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# 添加 RequestId 中间件
app.add_middleware(RequestIdMiddleware)

@app.on_event("startup")
async def startup_db_client():
    """应用启动时连接数据库并初始化"""
    await connect_to_mongo()
    
    # 初始化数据库（首次启动时创建默认管理员）
    db = get_database()
    await init_database(db)

@app.on_event("shutdown")
async def shutdown_db_client():
    """应用关闭时断开数据库连接"""
    await close_mongo_connection()

# 注册 v1 路由
app.include_router(auth_v1_router)
app.include_router(user_v1_router)
app.include_router(note_v1_router)
app.include_router(cert_v1_router)
app.include_router(cert_upload_v1_router)
app.include_router(cert_refresh_v1_router)

# 系统接口
@app.get("/", tags=["系统"])
async def root():
    """服务信息"""
    return {
        "service": "SAC API",
        "version": "1.0.0",
        "status": "running",
        "api_style": "Volcengine",
        "docs": "/docs",
        "description": "所有业务接口采用 POST 方法，统一响应格式",
        "base_path": "/sac/v1"
    }

@app.get("/health", tags=["系统"])
async def health():
    """健康检查"""
    return {
        "status": "healthy",
        "database": "connected"
    }

